package threadlocal;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Classname ThreadLocalNormalUsage03
 * @Description 在02的基础上优化，避免重复创建SimpleDateFormat，但是出现时间重复问题
 * @Date 2024/1/8 21:38
 * @Author zhuzhenguo
 */
public class ThreadLocalNormalUsage03 {
    public static ExecutorService threadPool = Executors.newFixedThreadPool(10);

    /**
     * 日期格式
     * 使用了同一个dateFormat出现时间重复问题
     * 1970-01-01 08:16:32
     * 1970-01-01 08:16:32
     * 1970-01-01 08:16:26
     * 1970-01-01 08:16:26
     */
    static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 1000; i++) {
            int finalI = i;
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    String date = new ThreadLocalNormalUsage03().date(finalI);
                    System.out.println(date);
                }
            });
        }
        threadPool.shutdown();
    }

    public String date(int seconds) {
        //参数的单位是毫秒，从1970.1.1 00:00:00 GMT计时
        Date date = new Date(1000L * seconds);
        return dateFormat.format(date);
    }
}
